#include <vector>
#include <string>

typedef std::vector<std::string> Board;


class NQueen {
public:
    std::vector<Board> solveNQueens(int n) {
        Board board(n, std::string(n, '.'));  // Q
        backtrack(board, 0);                  // BackTrack
        return res;
    }
private:
    bool isValid(Board& board, int row, int col) {
        int n = board.size();
        // 检查列是否有皇后冲突
        for (auto i = 0; i < row; i++) {
            if (board[i][col] == 'Q') {
                return false;
            }
        }
        
        // // 检查右上方是否有皇后互相冲突
        for (int i = row - 1, j = col + 1; 
                i >= 0 && j < n; i--, j++) {
            if (board[i][j] == 'Q')
                return false;
        }
        
        // // 检查左上方是否有皇后互相冲突
        for (int i = row - 1, j = col - 1;
                i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 'Q')
                return false;
        }
        return true;
    }

    void backtrack(Board& board, int row) {
        // 触发条件: 遍历到最后一行时退出
        if (row == board.size()) {  // 8
            res.push_back(board);     
            return;              
        }

        int n = board.size();
        for (int col = 0; col < n; ++col) {  // 
            if (!isValid(board, row, col)) 
                continue;                      // 盘某个位置是否有效
            board[row][col] = 'Q';             // 做选择
            backtrack(board, row + 1);
            board[row][col] = '.';             // 撤销决策
        }
    }
private:
    // std::vector<std::vector<std::string>> res;
    std::vector<Board> res;
};

int main(int argc, char* argv[]) {
    NQueen queen;   // queen, queue
    int   n = 9;
    auto res = queen.solveNQueens(n);

    for (auto &board : res) {
        for (auto& line : board) {
            printf("%s\n", line.c_str());
        }
        printf("==============================\n");
    }
    printf("Total %ld results!\n", res.size());
    return 0;
}